package br.uvv.Dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.primefaces.model.SortOrder;

import br.uvv.Enums.SituClientePortal;
import br.uvv.Model.ClientePortal;
import br.uvv.Util.DAOException;

@SuppressWarnings("unchecked")
public class ClientePortalDAO extends DAO {

	private static final long serialVersionUID = 1644593689725160930L;

	public ClientePortal selecionar(Long id) throws DAOException  {
		return (ClientePortal) get(ClientePortal.class, id);
	}
	
	public List<ClientePortal> listar() throws DAOException{
		return (List<ClientePortal>) list(ClientePortal.class);
	}
	
	public void salvar(ClientePortal clientePortalInstance) throws DAOException {
		save(clientePortalInstance, clientePortalInstance.getId());
	}
	
	public void remover(ClientePortal clientePortalInstance) throws DAOException {
		delete(ClientePortal.class, clientePortalInstance.getId());
	}
	
	public List<ClientePortal> listar(int first, int pageSize, String sortField, 
			SortOrder sortOrder, String nome) throws DAOException{
		Criterion[] filtros = { Restrictions.ilike("nomeCurto", "%" + nome + "%") };
		return (List<ClientePortal>) listPaginator(first, pageSize, sortField, sortOrder, ClientePortal.class, null, filtros);
	}
	
	public Integer count(String nome) throws DAOException {
		Criterion[] filtros = { Restrictions.ilike("nomeCurto", "%" + nome + "%") };
		return rowCount(ClientePortal.class, filtros);
	}

	public ClientePortal selecionarPorUsuarioResponsavel(Long id) throws DAOException {
		Criterion[] filtros = { Restrictions.eq("responsavel.id", id) };
		return (ClientePortal) get(ClientePortal.class, null, filtros);
	}

	public ClientePortal selecionarComUsuarios(Long id) throws DAOException {
		return (ClientePortal) get(ClientePortal.class, id, "usuarios");
	}

	public List<ClientePortal> listar(int first, int pageSize, String sortField,
			SortOrder sortOrder, String varNome, String varUsuario,
			Date varCadastroDe, Date varCadastroAte) throws DAOException {
		List<ClientePortal> modelList = new ArrayList<ClientePortal>();
		try {
			begin();
			Criteria criteria = sessao.createCriteria(ClientePortal.class);
			criteria.setFirstResult(first);
			criteria.setMaxResults(pageSize);
			criteria.add(Restrictions.or(Restrictions.ilike("nomeCurto", "%" + varNome + "%"), Restrictions.ilike("nomeCompleto", "%" + varNome + "%")));
			criteria.createCriteria("responsavel").add(Restrictions.or(Restrictions.ilike("nomeCurto", "%" + varUsuario + "%"), Restrictions.ilike("nomeCompleto", "%" + varUsuario + "%")));
			if (varCadastroDe != null)
				criteria.add(Restrictions.ge("dataCadastro", varCadastroDe));
			if (varCadastroAte != null)
				criteria.add(Restrictions.ge("dataCadastro", varCadastroAte));
			criteria.add(Restrictions.eq("situacao", SituClientePortal.PendenteAprovacao));
			String[] sortFields;
			if (sortField != null) {
				sortFields = sortField.split("[/.]");
				if (sortFields.length > 1){
					if (sortOrder.equals(SortOrder.DESCENDING)){
						criteria.createCriteria(sortFields[0]).addOrder(Order.desc(sortFields[1]));
					} else if (sortOrder.equals(SortOrder.ASCENDING)){
						criteria.createCriteria(sortFields[0]).addOrder(Order.asc(sortFields[1]));
					}
				} else {
					if (sortOrder.equals(SortOrder.DESCENDING)){
						criteria.addOrder(Order.desc(sortField));
					} else if (sortOrder.equals(SortOrder.ASCENDING)){
						criteria.addOrder(Order.asc(sortField));
					}
				}
			}
			modelList = criteria.list();
			commit();
		} catch (Exception e) {
			System.out.println("ERRO/DAO - ListPaginator -> " + ClientePortal.class.toString());
			throw new DAOException(e);
		}
		return modelList;
	}

	public Integer count(String varNome, String varUsuario, Date varCadastroDe,
			Date varCadastroAte) throws DAOException {
		Long count = 0l;
		try {
			begin();
			Criteria criteria = sessao.createCriteria(ClientePortal.class);
			criteria.setProjection(Projections.rowCount());
			criteria.add(Restrictions.or(Restrictions.ilike("nomeCurto", "%" + varNome + "%"), Restrictions.ilike("nomeCompleto", "%" + varNome + "%")));
			criteria.createCriteria("responsavel").add(Restrictions.or(Restrictions.ilike("nomeCurto", "%" + varUsuario + "%"), Restrictions.ilike("nomeCompleto", "%" + varUsuario + "%")));
			if (varCadastroDe != null)
				criteria.add(Restrictions.ge("dataCadastro", varCadastroDe));
			if (varCadastroAte != null)
				criteria.add(Restrictions.ge("dataCadastro", varCadastroAte));
			criteria.add(Restrictions.eq("situacao", SituClientePortal.PendenteAprovacao));
			count = (Long)criteria.uniqueResult();
			commit();
		} catch (Exception e) {
			System.out.println("ERRO/DAO - RowCount -> " + ClientePortal.class.toString());
			e.printStackTrace();
		}
		return Integer.parseInt(count.toString());
	}

	public ClientePortal selecionarComResponsavel(Long id) throws DAOException {
		ClientePortal modelInstance = new ClientePortal();
		try {
			begin();
			modelInstance = (ClientePortal) this.sessao.createCriteria(ClientePortal.class)
					.add(Restrictions.eq("id", id))
					.createCriteria("responsavel")
					.setFetchMode("perfil", FetchMode.JOIN)
					.uniqueResult();
			commit();
			return modelInstance;
		} catch(Exception e){
			e.printStackTrace();
			throw new DAOException(e);
		}
	}
}
